<template>
  <div class="auhorized-officer">
    <div class="dept-box" :class="{ isAdd: add }">
      <div class="left-dept">
        <tree-select
          ref="leftTree"
          v-model:value="deptIdLeft"
          :options="deptOptionsLeft"
          placeholder="请选择部门"
          default-expand-all
          :objMap="{ value: 'id', label: 'name', children: 'children' }"
        />
      </div>
      <div class="right-dept">
        <!-- <tree-select
          :disabled="true"
          ref="rightTree"
          v-model:value="deptIdLeft"
          :options="deptOptionsRight"
          placeholder="请选择部门"
          default-expand-all
          :objMap="{ value: 'id', label: 'name', children: 'children' }"
        /> -->
      </div>
    </div>
    <div>
      <el-transfer
        ref="transfer"
        v-model="rightValue"
        filterable
        :left-default-checked="[]"
        :right-default-checked="[]"
        :titles="['待授权人员', '已授权人员']"
        :props="{
          key: 'id',
          label: 'name',
        }"
        :data="data"
        @change="handleChange"
      />
    </div>
  </div>
</template>

<script setup name="AuthorizedOfficer">
import { deepClone, removeDuplicateObj } from '@/utils'
import { getDeptTrees } from '@/api/core'
import { getOrganizationAll } from '@/api/base'
const emits = defineEmits()
const deptOptionsLeft = ref(undefined)
// const deptOptionsRight = ref(undefined)
const { proxy } = getCurrentInstance()

const props = defineProps({
  add: {
    type: Boolean,
    default: false,
  },
  officer: {
    type: Object,
    default: () => {
      return {}
    },
  },
  currentGroup: {
    type: Object,
    default: () => {
      return {}
    },
  },
})
const _currentGroup = computed(() => {
  return props.currentGroup
})
// 右边选中人员数据
const rightValue = ref([])
const rightValueTemp = ref([])
const data = ref([])
const allLeftPerson = ref([])
const selectPerson = ref([])
// 右边选中人员备份（用于提交）
const selectPersonTemp = ref([])
const deptIdLeft = ref('')
const deptIdRight = ref('')

const _officer = computed(() => {
  const portfolioUserMapperVoList = props.officer.portfolioUserMapperVoList
  if (portfolioUserMapperVoList) {
    // 设置已授权人员
    rightValue.value = portfolioUserMapperVoList.map((element) => {
      return element.userId
    })
  }
  return props.officer
})

watch(_officer, (val) => {
  //设置左边待授权人员
  data.value = val.sysUserList
  selectPersonTemp.value = val.portfolioUserMapperVoList || []
  emits('confirmBtnPerson', val.portfolioUserMapperVoList)
})
watch(deptIdLeft, (val) => {
  if (!val) {
    // 设置已授权人员
    rightValue.value = selectPersonTemp.value.map((element) => {
      return element.userId
    })
  }
  getList(val)
})

/** 查询部门下拉树结构 */
function getTreeselect() {
  getDeptTrees().then((response) => {
    deptOptionsLeft.value = deepClone(response.data)
    // deptOptionsRight.value = deepClone(response.data)
  })
}
function filterRightPerson(val) {
  // 过滤属于右边部门的人员
  const filterPerson = selectPersonTemp.value.filter((element) => {
    return element.deptId === val
  })
  const personUserId = filterPerson.map((element) => {
    return element.userId
  })
  rightValue.value = personUserId
  // 清空设置之前所有选择的数据
  if (!val) {
    rightValue.value = selectPersonTemp.value.map((element) => {
      return element.userId
    })
  }
}
/** 查询用户列表 */
function getList(deptId) {
  const params = {
    sort: 'create_time desc',
    searchType: 'user',
    deptId: deptId === -1 ? '' : deptId,
    statusMult: '0,1',
    type: 'normal',
    orgId: proxy.$store.state.user.userInfo.user.orgId,
  }
  getOrganizationAll(params).then((res) => {
    data.value = res.data
    rightValue.value = selectPersonTemp.value.map((element) => {
      return element.userId
    })
  })
}
function handleChange(value, direction, movedKeys) {
  selectPerson.value = handelParmas(value)
  let allPerson = []
  if (direction === 'right') {
    // 向右添加
    selectPersonTemp.value = deepClone(
      selectPersonTemp.value.concat(selectPerson.value)
    )
  } else {
    // 移除
    selectPersonTemp.value = removePerson(movedKeys)
  }
  allPerson = removeDuplicateObj(selectPersonTemp.value, 'userId')
  emits('confirmBtnPerson', allPerson)
}
function removePerson(movedKeys) {
  let person = deepClone(selectPersonTemp.value)
  movedKeys.forEach((item) => {
    person = filterPersonLeft(person, item)
  })

  return person
}
// 过滤用户
function filterPersonLeft(arr, userId) {
  return arr.filter((element) => {
    return userId != element.userId
  })
}
function handelParmas(value) {
  let personArr = []
  value.forEach((element) => {
    data.value.forEach((item) => {
      if (item.id === element) {
        personArr.push({
          userName: item.name,
          deptId: item.deptId,
          filePortfolioId: _currentGroup.value.id,
          userId: item.id,
        })
      }
    })
  })
  return personArr
}
function clearHandle() {
  deptIdLeft.value = ''
  proxy.$refs.transfer.clearQuery('left')
  proxy.$refs.transfer.clearQuery('right')
}
getTreeselect()
defineExpose({
  rightValue,
  data,
  clearHandle,
})
</script>

<style lang="scss" scoped>
.auhorized-officer {
  display: flex;
  justify-content: space-around;
  flex-direction: column;
  align-items: center;
  .dept-box {
    width: 534px;
    display: flex;
    justify-content: space-between;
    .left-dept,
    .right-dept {
      display: flex;
      align-items: center;
      justify-content: space-around;
      margin-bottom: 10px;
      width: 200px;
    }
  }
  .isAdd {
    /* width: 52.5%; */
  }
}
</style>
